import { Component, OnInit, Input } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

@Component({
  selector: 'app-dynamic-form',
  templateUrl: './dynamic-form.component.html',
  styleUrls: ['./dynamic-form.component.scss']
})
export class DynamicFormComponent implements OnInit {
  @Input() schemas: any
  validateForm!: FormGroup
  valildValue = {} as any
  errorMsg = {} as any
  constructor(private fb: FormBuilder) { }
  submit() {
    if (this.validateForm.valid) {
      return this.validateForm.value
    } else {
      Object.values(this.validateForm.controls).forEach(control => {
        this.errorMsg[control.errors?.['field']] = {msg: control.errors?.['msg']}
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true});
        }
      })
    }
  }
  ngOnInit(): void {
    this.schemas.fieldList.forEach((item: any) => {
      if(item.required && item.rules) {
        let inputType = ['Input', 'InputNumber', 'InputTextArea']
        this.errorMsg[item.field] = {msg: inputType.includes(item.component) ? `请输入${item.label}` : `请选择${item.label}`}
        this.valildValue[item.field] = [null, [Validators.required, item.rules]]
      } else {
        this.valildValue[item.field] = [null]
      }
    });
    this.validateForm = this.fb.group(this.valildValue)
    
  }

}
